<template>
  <view class="container">
    <view class="edit-cart" @click="toggleEdit">编辑购物车</view>
    <view class="cart-list">
      <view v-for="(item, index) in sortedCartList" :key="index" class="cart-item-card">
        <view class="item-check" :class="{'checked': item.check === '1'}" @click="toggleCheck(item)">
          <view class="checkbox-circle">
            <text class="icon-check" v-if="item.check === '1'">✔</text>
          </view>
        </view>
        <view class="item-info">
          <image class="item-img" :src="item.img" mode="aspectFit"></image>
          <view class="item-detail">
            <view class="item-name">{{ item.name }}</view>
            <view class="item-price">
              <view class="item-price2">
                <text class="discount-price" v-if="item.discount_price">￥{{ parseFloat(item.discount_price).toFixed(2) }}</text>
                <text class="original-price" v-if="item.discount_price">￥{{ parseFloat(item.original_price).toFixed(2) }}</text>
                <text class="original-price2" v-else>￥{{ parseFloat(item.original_price).toFixed(2) }}</text>
              </view>
              <view class="item-quantity-control">
                <button @click="decreaseQuantity(item)" class="quantity-button">-</button>
                <view class="quantity-display">{{ item.quantity }}</view>
                <button @click="increaseQuantity(item)" class="quantity-button">+</button>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view v-if="sortedCartList.length === 0" class="no-data">购物车为空</view>
    </view>
    <view class="cart-footer">
      <view class="footer-left">
        <view class="select-all-container">
          <view class="select-all" :class="{'checked': isAllChecked}" @click="selectAll">
            <view class="checkbox-circle">
              <text class="icon-check" v-if="isAllChecked">✔</text>
            </view>
          </view>
          <text class="select-text">全选</text>
        </view>
      </view>
      <view class="footer-right">
        <view class="total-and-checkout">
          <view v-if="!isEditing" class="total-price">总价：￥{{ totalPriceFormatted }}</view>
          <button v-if="!isEditing" @click="checkout" class="checkout-button">结算</button>
          <button v-else @click="deleteCart" class="delete-button">删除</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cartList: [],
      totalPrice: 0.00,
      isAllChecked: false,
      isEditing: false
    };
  },
  onLoad() {
    this.fetchCartData();
  },
  onShow() {
    this.fetchCartData();
  },
  computed: {
    sortedCartList() {
      return this.cartList.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));
    },
    totalPriceFormatted() {
      return this.totalPrice.toFixed(2);
    }
  },
  methods: {
   fetchCartData() {
     const token = uni.getStorageSync('Authorization');
     const url = 'http://localhost:8887/Shoppingcart/Userselect';
     const header = {
       'Authorization': token,
       'Content-Type': 'application/json',
     };
     uni.request({
       url,
       method: 'GET',
       header,
       success: (res) => {
         if (res.data.code === 200) {
           this.cartList = res.data.data;
           this.calculateTotalPrice();
           this.updateAllCheckedStatus();
           if (this.cartList.length === 0) {
             uni.showToast({
               title: '购物车为空',
               icon: 'none'
             });
           }
         } else if (res.data.status === 'unauthorized') {
           uni.showToast({
             title: '请登录！',
             icon: 'none'
           });
         } else {
           uni.showToast({
             title: '获取购物车数据失败',
             icon: 'none'
           });
         }
       },
       fail: () => {
         uni.showToast({
           title: '请求失败',
           icon: 'none'
         });
       }
     });
   },
    calculateTotalPrice() {
      this.totalPrice = this.sortedCartList.reduce((sum, item) => {
        const price = item.discount_price || item.original_price;
        return sum + (parseFloat(price) * parseInt(item.quantity, 10) * (item.check === '1' ? 1 : 0));
      }, 0);
    },
    toggleCheck(item) {
      item.check = item.check === '1' ? '0' : '1';
      this.updateCheck(item);
      this.updateAllCheckedStatus();
    },
    updateCheck(item) {
      const token = uni.getStorageSync('Authorization');
      const url = `http://localhost:8887/Shoppingcart/updatecheck?id=${item.id}`;
      const header = {
        'Authorization': token,
        'Content-Type': 'application/json',
      };
      uni.request({
        url,
        method: 'POST',
        header,
        success: (res) => {
          if (res.data.success) {
            this.calculateTotalPrice();
          } else {
            uni.showToast({
              title: '修改失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    },
    increaseQuantity(item) {
      if (item.quantity < 100) {
        item.quantity++;
        this.updateQuantity(item);
      }
    },
    decreaseQuantity(item) {
      if (item.quantity > 1) {
        item.quantity--;
        this.updateQuantity(item);
      }
    },
    updateQuantity(item) {
      const token = uni.getStorageSync('Authorization');
      const url = 'http://localhost:8887/Shoppingcart/updatequantity';
      const data = {
        id: item.id,
        quantity: item.quantity
      };
      const header = {
        'Authorization': token,
        'Content-Type': 'application/json',
      };
      uni.request({
        url,
        method: 'POST',
        header,
        data: JSON.stringify(data),
        success: (res) => {
          if (res.data.success) {
            this.calculateTotalPrice();
          } else {
            uni.showToast({
              title: '修改失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    },
    selectAll() {
      const token = uni.getStorageSync('Authorization');
      const url = 'http://localhost:8887/Shoppingcart/updatecheckall';
      const header = {
        'Authorization': token,
        'Content-Type': 'application/json',
      };
      uni.request({
        url,
        method: 'POST',
        header,
        success: (res) => {
          if (res.data.success) {
            this.fetchCartData();
          } else {
            uni.showToast({
              title: '全选失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    },
    checkout() {
      uni.navigateTo({
        url: '/pages/settlement/settlement'
      });
    },
    deleteCart() {
      const token = uni.getStorageSync('Authorization');
      const url = 'http://localhost:8887/Shoppingcart/delete';
      const header = {
        'Authorization': token,
        'Content-Type': 'application/json',
      };
      uni.request({
        url,
        method: 'POST',
        header,
        success: (res) => {
          if (res.data.success) {
			   uni.showToast({
			            title: '删除成功',
			            icon: 'success',
			          });
			          this.fetchCartData();
          } else {
            uni.showToast({
              title: '删除失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    },
    toggleEdit() {
      this.isEditing = !this.isEditing;
    },
    updateAllCheckedStatus() {
      this.isAllChecked = this.sortedCartList.length > 0 && this.sortedCartList.every(item => item.check === '1');
    }
  }
};
</script>

<style>
.container {
  padding: 10px;
  position: relative;
}
.cart-list {
  margin-bottom: 120px;
  margin-top: 37px;
}
.cart-item-card {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
padding: 10px;
border: 1px solid #eee;
border-radius: 5px;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.item-check {
width: 24px;
height: 24px;
border-radius: 50%;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
margin-right: 10px;
cursor: pointer;
}
.item-check.checked {
background-color: #3cc51f;
border-color: #3cc51f;
}
.item-check .icon-check {
color: #fff;
font-size: 14px;
}
.item-info {
flex: 1;
display: flex;
flex-direction: row;
justify-content: center;
}
.item-img {
width: 80px;
height: 80px;
margin-bottom: 10px;
}
.item-detail {
flex: 1;
margin-left: 10px;
}
.item-name {
font-size: 16px;
font-weight: bold;
}
.item-price {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 5px;
}
.item-price2 {
display: flex;
flex-direction: column;
}
.original-price {
text-decoration: line-through;
color: #999;
}
.original-price2 {
color: red;
font-size: 18px;
}
.discount-price {
color: red;
font-size: 18px;
}
.item-quantity-control {
display: flex;
align-items: center;
margin-top: 5px;
}
.quantity-button {
font-size: 22px;
padding: 0;
width: 30px;
height: 30px;
line-height: 30px;
text-align: center;
background: none;
border: none;
cursor: pointer;
}
.quantity-display {
margin: 0 10px;
font-size: 14px;
}
.cart-footer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
background-color: #fff;
border-top: 1px solid #eee;
z-index: 10;
}
.footer-left {
display: flex;
align-items: center;
flex-grow: 1;
}
.select-all-container {
display: flex;
align-items: center;
margin-right: 10px;
}
.select-text {
font-size: 16px;
}
.select-all {
width: 24px;
height: 24px;
border-radius: 50%;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.select-all.checked {
background-color: #3cc51f;
border-color: #3cc51f;
}
.select-all .icon-check {
color: #fff;
font-size: 14px;
}
.edit-cart {
display: flex;
justify-content: flex-end;
position: fixed;
top: 0;
right: 0px;
left: 0px;
background-color: #F8F8F8;
color: black;
padding: 10px;
font-size: 18px;
cursor: pointer;
z-index: 100;
}
.footer-right {
display: flex;
align-items: center;
justify-content: flex-end;
}
.total-and-checkout {
display: flex;
align-items: center;
width: 100%;
}
.total-price {
font-size: 18px;
font-weight: bold;
margin-right: 10px;
}
.checkout-button {
background-color: red;
color: white;
border-radius: 20px;
padding: 5px 20px;
font-size: 16px;
margin-left: 10px;
}
.delete-button {
background-color: red;
color: white;
border-radius: 20px;
padding: 5px 20px;
font-size: 16px;
margin-left: 10px;
}
.no-data {
text-align: center;
padding: 20px;
font-size: 16px;
color: #999;
}
</style>